import re
import base64
import requests

from mitmproxy import ctx

proxyInfo = None

def get_proxy():
    global proxyInfo
    if proxyInfo == None:
        proxyInfo = requests.get("http://http.tiqu.alicdns.com/getip3?num=1&type=1&pro=&city=0&yys=0&port=11&pack=110824&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1&regions=&gm=4").text
    ctx.log.info("proxyInfo:%s" % proxyInfo)
    return proxyInfo

def delete_proxy(proxy):
    requests.get("http://127.0.0.1:5010/delete/?proxy={}".format(proxy))

detectList = [  'driver-evaluate',
                'webdriver',
                '__webdriver_script_fn',
                'webdriverScriptFn',
                'cookieChromeDriver',
                '__webdriver_unwrapped',
                '_WEBDRIVER_ELEM_CACHE',
                '__$webdriverAsyncExecutor',
                '__lastWatirConfirm',
                '__lastWatirPrompt',
                '$chrome_asyncScriptInfo',
                '$cdc_asdjflasutopfhvcZLmcfl_',

                  'webdriver-evaluate',
                  'selenium-evaluate',
                  'webdriverCommand',
                  'webdriver-evaluate-response',
                 # '__driver_evaluate',
                  '__webdriver_evaluate',
                 # '__webdriver_script_fn',
                  '__selenium_evaluate',
                  '__fxdriver_evaluate',
                  '__driver_unwrapped',
                  '__selenium_unwrapped',
                  '__fxdriver_unwrapped',
                  '_Selenium_IDE_Recorder',
                  '_selenium',
                  'calledSelenium',
                  'ChromeDriverw',
                  'driver-evaluate',
                  'webdriver-evaluate',
                  'selenium-evaluate',
                  'webdriverCommand',
                  'webdriver-evaluate-response',
                  '__webdriverFunc',
                  '__lastWatirAlert'
              ]

def response(flow):
    #if '.js1' in flow.request.url:
    ctx.log.info("Response code:{%s}" % flow.response.status_code)
    if 'general_page' in flow.request.url:
        ctx.log.info("==============request url:{%s}" % flow.request.url)
        start =  flow.response.text.find("<script>") + len("<script>")
        ctx.log.info("found start:%d" % start)
        inspect = "Object.defineProperty(navigator, 'webdriver', {get:()=>undefined});"
        front = flow.response.text[0:start]
        end = flow.response.text[start + len("<script>"):]

        flow.response.text = front + inspect + end

        #print("request text:{%s}" % flow.response.text)
        for key in detectList:
            #print('found key:%s' % key)
            encodeKey = str(base64.b64encode(key.encode("utf-8")), "utf-8")
            nosuchattr = '"NO-SUCH-ATTR"'
            encodeNoAttr = str(base64.b64encode(nosuchattr.encode("utf-8")), "utf-8")
            #ctx.log.info("encodeNoAttr:%s" % encodeNoAttr)
            #if encodeKey in flow.response.text:
            #    ctx.log.info('found key:%s========' % key)
            #    nosuchattr = '"NO-SUCH-ATTR"'
            #    flow.response.text = flow.response.text.replace('"{}"'.format(encodeKey), str(encodeNoAttr, "utf-8"))

            #if key in flow.response.text:
            #    ctx.log.info('found key:%s' % key)
            #    flow.response.text = flow.response.text.replace('"{}"'.format(key), 'userAgent')
        #flow.response.text = flow.response.text.replace('t.webdriver', 'false')
        #flow.response.text = flow.response.text.replace('ChromeDriver', '')

#def request(flow):
#    print("开始修改ip")

#    proxy = get_proxy().split(":", 1)
#    proxy_ip = proxy[0]
#    ctx.log.info("ip: %s---" % proxy_ip)
#    proxy_port = int(proxy[1])
#    ctx.log.info("port:%d----" %proxy_port)
    # 这里配置二级代理的ip地址和端口
#    if flow.live:
#        print("设置代理")
#        flow.live.change_upstream_proxy_server((proxy_ip, proxy_port))